package com.lykj.llw.box.ui.diafrg

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ScreenUtils
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.lykj.lib_base.base.BaseDiaFrg
import com.lykj.lib_base.component.GlideApp
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.PackageUtils
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.llw.box.R
import com.lykj.llw.box.databinding.DiafrgShareBinding
import com.lykj.llw.box.utils.Util
import com.tencent.connect.share.QQShare
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.tencent.tauth.IUiListener
import com.tencent.tauth.Tencent
import com.tencent.tauth.UiError
import me.jessyan.autosize.utils.AutoSizeUtils


/**
 * ================================================
 * 分享弹窗
 * ================================================
 *
 * @author gosha
 * @date 2023/12/1-11:11
 */
class ShareDiaFrg : BaseDiaFrg() {
    lateinit var binding: DiafrgShareBinding

    private val WX_APP_ID = "wxd5f396e1b273d83a"
    private val QQ_APP_ID = "1112169242"

    // IWXAPI 是第三方app和微信通信的openApi接口
    private var api: IWXAPI? = null
    private var mTencent: Tencent? = null

    private var mShareUrl = ""
    private var mTitle = ""
    private var mSummery = ""
    private var mImgUrl = ""
    private var bitmap: Bitmap? = null

    override fun onStart() {
        super.onStart()
        val window = dialog!!.window
        //设置窗口弹出动画
        window!!.setWindowAnimations(0)
        val layoutParams = window.attributes
        layoutParams.apply {
            dimAmount = 0.5f
            gravity = Gravity.BOTTOM
            width = WindowManager.LayoutParams.MATCH_PARENT
            height = WindowManager.LayoutParams.WRAP_CONTENT
        }


        if (null != dialog) {
            val dm = DisplayMetrics()
            requireActivity().windowManager.defaultDisplay.getMetrics(dm)
            dialog?.apply {
                setCanceledOnTouchOutside(true)
                window.setGravity(Gravity.BOTTOM)
                window.setLayout(
                    ScreenUtils.getScreenWidth(),
                    AutoSizeUtils.dp2px(requireContext(), 125f)
                )
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DiafrgShareBinding.inflate(layoutInflater)
        initUI()
        initData()
        setListener()
        return binding.root
    }

    override fun initUI() {
    }

    override fun initData() {
        // 将应用的appId注册到微信
        api = WXAPIFactory.createWXAPI(requireContext(), WX_APP_ID, true)
        api?.registerApp(WX_APP_ID);
        mTencent = Tencent.createInstance(QQ_APP_ID, requireContext())
        Tencent.setIsPermissionGranted(true)

//        mShareUrl =
//            "http://hezi-h5.66wsy.com/hezi_register?param=1-${BaseApplication.instance?.getUserInfo()?.channelId}-${BaseApplication.instance?.getUserInfo()?.id}"
    }

    open fun setShareParam(
        title: String,
        summery: String,
        imgUrl: String,
        shareUrl: String
    ): ShareDiaFrg {
        this.mShareUrl = shareUrl
        this.mTitle = title
        this.mSummery = summery
        this.mImgUrl = imgUrl
        return this
    }

    private fun shareToWX() {
        //初始化一个WXWebpageObject，填写url
        val webpage = WXWebpageObject()
        webpage.webpageUrl = mShareUrl

        //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
        val msg = WXMediaMessage(webpage)
        msg.title = mTitle
        msg.description = mSummery
        if (null == bitmap) {
            val bmp = BitmapFactory.decodeResource(resources, R.drawable.ic_small_app_icon)
            msg.thumbData = Util.bmpToByteArray(bmp, true)
        } else {
            msg.thumbData = Util.bmpToByteArray(bitmap, true)
        }

        //构造一个Req
        val req = SendMessageToWX.Req()
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession

        //调用api接口，发送数据到微信
        api!!.sendReq(req)
    }

    private fun shareToQQ() {
        val params = Bundle()
        params.putString(
            QQShare.SHARE_TO_QQ_TARGET_URL,
            mShareUrl
        )
        params.putString(QQShare.SHARE_TO_QQ_TITLE, mTitle);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "攒趣")
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, mSummery)
        if (mImgUrl.isNotEmpty()) {
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, mImgUrl)
        }
        mTencent?.shareToQQ(requireActivity(), params, object : IUiListener {
            override fun onComplete(p0: Any?) {
                LogUtils.e("qq分享完成")
                ToastUtils.showShort(requireContext(), "QQ分享成功")
            }

            override fun onError(p0: UiError?) {
                LogUtils.e("qq分享错误:${p0?.errorDetail}")
            }

            override fun onCancel() {
                LogUtils.e("qq分享取消")
            }

            override fun onWarning(p0: Int) {
                LogUtils.e("qq分享警告")
            }
        })
    }

    override fun setListener() {
        binding.lltWx.clickWithTrigger(200) {
            if (PackageUtils.checkApk(requireContext(), "com.tencent.mm")) {
                if (mImgUrl.isNotEmpty()) {
                    GlideApp.with(this)
                        .asBitmap()
                        .load(mImgUrl)
                        .listener(object : RequestListener<Bitmap> {
                            override fun onLoadFailed(
                                e: GlideException?,
                                model: Any?,
                                target: Target<Bitmap>?,
                                isFirstResource: Boolean
                            ): Boolean {
                                return false
                            }

                            override fun onResourceReady(
                                resource: Bitmap?,
                                model: Any?,
                                target: Target<Bitmap>?,
                                dataSource: DataSource?,
                                isFirstResource: Boolean
                            ): Boolean {
                                bitmap = Bitmap.createBitmap(resource!!)
                                shareToWX()
                                return true
                            }
                        }).submit(100, 100)
                } else {
                    shareToWX()
                }
            } else {
                ToastUtils.showShort(requireContext(), "微信未安装")
            }
        }

        binding.lltQq.clickWithTrigger(200) {
            if (PackageUtils.checkApk(
                    requireContext(),
                    "com.tencent.mobileqq"
                ) || PackageUtils.checkApk(
                    requireContext(),
                    "com.tencent.tim"
                )
            ) {
                shareToQQ()
            } else {
                ToastUtils.showShort(requireContext(), "QQ未安装")
            }
        }

        binding.lltLink.clickWithTrigger(200) {
            //FIXME:复制分享链接
            ClipboardUtils.copyText(mShareUrl)
            ToastUtils.showShort(requireContext(), "复制链接成功")
        }
    }

    override fun onDestroy() {
        removeDisposables(this)
        bitmap?.recycle()
        super.onDestroy()
    }
}